<?php

/**
 * 零担货单
 * Class GoodslessApp
 */

class GoodslessApp extends BackendApp
{
	var $_goodsnormal_mod;
	var $_goodsnormalsub_mod;
	var $_dictionary_mod;
	function __construct()
	{
		$this->GoodslessApp();
	}

	function GoodslessApp()
	{
		parent::BackendApp();
		$this->_goodsnormal_mod =& m('goodsnormal');
		$this->_goodsnormalsub_mod =& m('goodsnormalsub');
		$this->_dictionary_mod =& m('dictionary');
	}

	function index()
	{
		$conditions = "1=1 and g_type='零担'";
		$g_code = isset($_GET['g_code']) && !empty($_GET['g_code'])? trim($_GET['g_code']):'';
		$g_owner = isset($_GET['g_owner']) && !empty($_GET['g_owner'])? trim($_GET['g_owner']):'';

		if(!empty($g_code)){
			$conditions.=" and g_code like '%".$g_code."%'";
		}
		if(!empty($g_owner)){
			$conditions.=" and g_owner like '%".$g_owner."%'";
		}
		$user_ids = $this->checkpower();
		if(!empty($user_ids)){
			$conditions.=" and g_optid in(".$user_ids.")";
		}
		$page   =   $this->_get_page(10);   //获取分页信息

		//ws_tid是指货单是否被运单提取
		$sql="SELECT n.*,m.user_name,IFNULL(x.ws_tid,0) as ws_tid FROM zys_goods_normal n LEFT JOIN zys_member m ON n.g_optid=m.user_id LEFT JOIN (SELECT ws_tid,IFNULL(ws_gid,0) as ws_gid from zys_waybill_sub_normal GROUP BY ws_gid) x on n.g_tid=ws_gid	where $conditions ORDER BY g_opdate DESC limit $page[limit]";

		$goodsless=$this->_goodsnormal_mod->getAll($sql);

		$sql="SELECT count(*) as num FROM zys_goods_normal n LEFT JOIN zys_member m ON n.g_optid=m.user_id LEFT JOIN (SELECT ws_tid,IFNULL(ws_gid,0) as ws_gid from zys_waybill_sub_normal GROUP BY ws_gid) x on n.g_tid=ws_gid	where $conditions";

		$db = &db();

		$num = $db->getOne($sql);

		$page['item_count']=  $num; //获取统计数据

		$this->_format_page($page);

		$this->assign('page_info', $page);   //将分页信息传递给视图，用于形成分页条
		$this->assign('goodsless', $goodsless);
		$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
		$this->assign('tabself', json_encode(array('text'=>'零担货单管理')));
		$this->display('goodsless.index.html');
	}

	//新增
	function add(){
		//货单id
		$id = isset($_GET['id'])?intval($_GET['id']):0;
		$this->assign('g_tid',$id);
		//是否提交
		$isbool = 1;
		if (!IS_POST){
			$gt=array();
			$goodstype=$this->_dictionary_mod->find(array(
				'fields'   => 'this.d_value',
				'conditions'  => "d_code='goodstype'",
			));

			if($goodstype){
				foreach($goodstype as $v){
					$gt[$v['d_value']]=$v['d_value'];
				}
			}
			$this->assign('goodstype', $gt);
			$goodsless=array();
			if(!empty($id)){
				$sql=" SELECT n.*,m.user_name,IFNULL(x.ws_tid,0) as ws_tid FROM zys_goods_normal n LEFT JOIN zys_member m ON n.g_optid=m.user_id LEFT JOIN (SELECT ws_tid,IFNULL(ws_gid,0) as ws_gid from zys_waybill_sub_normal GROUP BY ws_gid) x on n.g_tid=ws_gid where g_tid=".$id;
				$goodsless=$this->_goodsnormal_mod->getRow($sql);
				if($goodsless['ws_tid'] !=0){
					$isbool =0;
				}
				$goodssub =  $this->_goodsnormalsub_mod->find(
					array(
						'fields'=> 'this.*',
						'conditions'  => 'gs_gtid='.$id,
					)
				);
				$this->assign('goodssub', $goodssub);
				$db = &db();
				//是否有已拆分货物
				$sql = "select * from zys_goods_normal_sub where g_gstid!='' and gs_gtid =".$id;
				$remove = $db->getAll($sql);
				$this->assign('remove', $remove);
			}else{
				$goodsless['g_code']='T'.gmtime();
				$goodsless['g_opdate']=gmtime();
				$goodsless['user_name']=$this->visitor->get('user_name');
			}
			$this->assign('auth', $goodsless);
			$this->assign('isbool', $isbool);
			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js,jquery.plugins/jquery.validate.js',
        'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
			$this->assign('tabself', json_encode(array('text'=>'新建货单')));
			$this->assign('tabback', json_encode(array('text'=>'货单管理','url'=>'')));
			$this->display('goodsless.form.html');
		}else{
			$gs_gtid = isset($_POST['gs_gtid']) && !empty($_POST['gs_gtid']) ? intval($_POST['gs_gtid']): 0;//货单id
			$g_owner = isset($_POST['g_owner']) && !empty($_POST['g_owner']) ? trim($_POST['g_owner']): '';
			$g_owner_tel = isset($_POST['g_owner_tel']) && !empty($_POST['g_owner_tel']) ?trim($_POST['g_owner_tel']):'';
			$g_loading_place = isset($_POST['g_loading_place']) && !empty($_POST['g_loading_place']) ?trim($_POST['g_loading_place']):'';
			$g_loading_lng = isset($_POST['g_loading_lng']) && !empty($_POST['g_loading_lng']) ?trim($_POST['g_loading_lng']):'';
			$g_loading_lat = isset($_POST['g_loading_lat']) && !empty($_POST['g_loading_lat']) ?trim($_POST['g_loading_lat']):'';
			$g_unloading_place = isset($_POST['g_unloading_place']) && !empty($_POST['g_unloading_place']) ?trim($_POST['g_unloading_place']):'';
			$g_unloading_lng = isset($_POST['g_unloading_lng']) && !empty($_POST['g_unloading_lng']) ?trim($_POST['g_unloading_lng']):'';
			$g_unloading_lat = isset($_POST['g_unloading_lat']) && !empty($_POST['g_unloading_lat']) ?trim($_POST['g_unloading_lat']):'';
			$g_consignee = isset($_POST['g_consignee']) && !empty($_POST['g_consignee']) ?trim($_POST['g_consignee']):'';
			$g_consignee_tel = isset($_POST['g_consignee_tel']) && !empty($_POST['g_consignee_tel']) ?trim($_POST['g_consignee_tel']):'';
			$g_consignor = isset($_POST['g_consignor']) && !empty($_POST['g_consignor']) ?trim($_POST['g_consignor']):'';
			$g_consignor_tel = isset($_POST['g_consignor_tel']) && !empty($_POST['g_consignor_tel']) ?trim($_POST['g_consignor_tel']):'';
			if(empty($g_owner) || empty($g_owner_tel) || empty($g_loading_place) || empty($g_unloading_place) || empty($g_consignee) || empty($g_consignee_tel) || empty($g_consignor) || empty($g_consignor_tel)){
				$this->show_warning('填写有误',   'index.php?app=goodsless&act=add');
			}
			$goods_array = array(
				'g_type'     => '零担',
				'g_status'   => '新建',
				'g_code'     => 'T'.gmtime(),
				'g_ownertid' => intval($_POST['g_ownertid']),
				'g_owner'    => $g_owner,
				'g_owner_tel'     => $g_owner_tel,
				'g_loading_place' => $g_loading_place,
				'g_loading_lng' => $g_loading_lng,
				'g_loading_lat' => $g_loading_lat,
				'g_unloading_place'    => $g_unloading_place,
				'g_unloading_lng' => $g_unloading_lng,
				'g_unloading_lat' => $g_unloading_lat,
				'g_consignee'     => $g_consignee,
				'g_consignee_tel' => $g_consignee_tel,
				'g_consignor'    => $g_consignor,
				'g_consignor_tel'    => $g_consignor_tel,
				'g_note'			=> trim($_POST['g_note']),
				'g_optid'      => $this->visitor->get('user_id'),
				'g_opdate'     => gmtime(),
				//'g_tgdate'     => gmstr2time($_POST['g_tgdate']),
				//'g_rdate'     => gmstr2time($_POST['g_rdate']),
				'g_loading_date'     => gmstr2time($_POST['g_loading_date']),
				'g_unloading_date'     => gmstr2time($_POST['g_unloading_date']),
				'g_gtype'    => trim($_POST['g_gtype'])
			);
			$userid = $this->visitor->get('user_id');
			$unit = $this->visitor->get('unit');
			if($gs_gtid){
				$g_tid = $gs_gtid;
				$tag=1;
				unset($goods_array['g_type']);
				unset($goods_array['g_status']);
				unset($goods_array['g_code']);
				$sql = "select * from zys_goods_normal where g_tid =".$g_tid;
				$db=&db();
				$good_row = $db->getrow($sql);
				$ower = $good_row['g_owner'];
				$num = $this->checkaddr($g_loading_place,$userid,$unit);
				if($num==0){
					$loading = array(
						'user_id'    	=>	$userid,
						'consignee' 	=>	$g_consignor,
						'address' 		=>	$g_loading_place,
						'phone_tel'	=>	$g_consignor_tel,
						'lng'			=>	$g_loading_lng,
						'lat'			=>	$g_loading_lat,
						'addrtype'		=>	'零担装货',
						'unit'			=>	$unit,
					);
					$this->addaddr($loading);
				}
				$num1 = $this->checkaddr($g_unloading_place,$userid,$unit);
				if($num1==0){
					$unloading = array(
						'user_id'    	=>	$userid,
						'consignee' 	=>	$g_consignee,
						'address' 		=>	$g_unloading_place,
						'phone_tel'	=>	$g_consignee_tel,
						'lng'			=>	$g_unloading_lng,
						'lat'			=>	$g_unloading_lat,
						'addrtype'		=>	'零担卸货',
						'unit'			=>	$unit,
					);
					$this->addaddr($unloading);
				}
				$this->_goodsnormal_mod->edit($gs_gtid,$goods_array);
				$normal=empty($_POST['normal'])?array():$_POST['normal'];
				if($normal){
					$normal_array=array_values($normal);
					foreach($normal_array as $v){
						$normal_sub = array(
							'gs_gtid' => $gs_gtid,
							'gs_name' => $v['gs_name'],
							'gs_piece' => $v['gs_piece'],
							'gs_weight'  => $v['gs_weight'],
							'gs_size'  => $v['gs_size'],
							'g_consignor'  => $ower,
						);
						if($v['gs_tid']){
							//修改
							$gs_tid = $v['gs_tid'];
							$this->_goodsnormalsub_mod->edit($gs_tid, $normal_sub);
						}else{
							//添加
							$gs_tid = $this->_goodsnormalsub_mod->add($normal_sub);
						
						}
					}
					if($this->_goodsnormal_mod->has_error()){
						$this->show_warning($this->_goodsnormal_mod->get_error(),'', 'index.php?app=goodsless&act=add&id=' . $g_tid);

						return;
					}
				}
			}else{
				$tag=2;
				$g_tid = $this->_goodsnormal_mod->add($goods_array);

				if($this->_goodsnormal_mod->has_error()){
					$this->show_warning($this->_goodsnormal_mod->get_error(),'', 'index.php?app=goodsless&act=add');

					return;
				}

				$num = $this->checkaddr($g_loading_place,$userid,$unit);
				if($num==0){
					$loading = array(
						'user_id'    	=>	$userid,
						'consignee' 	=>	$g_consignor,
						'address' 		=>	$g_loading_place,
						'phone_tel'	=>	$g_consignor_tel,
						'lng'			=>	$g_loading_lng,
						'lat'			=>	$g_loading_lat,
						'addrtype'		=>	'零担装货',
						'unit'			=>	$unit,
					);
					$this->addaddr($loading);
				}
				$num1 = $this->checkaddr($g_unloading_place,$userid,$unit);
				if($num1==0){
					$unloading = array(
						'user_id'    	=>	$userid,
						'consignee' 	=>	$g_consignee,
						'address' 		=>	$g_unloading_place,
						'phone_tel'	=>	$g_consignee_tel,
						'lng'			=>	$g_unloading_lng,
						'lat'			=>	$g_unloading_lat,
						'addrtype'		=>	'零担卸货',
						'unit'			=>	$unit,
					);
					$this->addaddr($unloading);
				}

			}
			
			if ($tag==1){
				$this->show_message('编辑成功','返回货单',   'index.php?app=goodsless&act=add&id=' . $g_tid
			);
			}else if ($tag==2){
				$this->show_message('添加成功','返回货单',   'index.php?app=goodsless&act=add&id=' . $g_tid
			);
			}
			

		}
	}

	//拆分货物
	function chooseless(){
		$db = &db();
		$type = $this->visitor->get('type');
		$unit = 0;
		if($type==4){
			$unit = $this->visitor->get('unit');
			$sql = "select o_name from zys_operator where o_carrier=1 and o_tid=".$unit;
			$o_name = $db->getOne($sql);
		}
		$this->assign('o_name', $o_name);
		$this->assign('unit', $unit);
		$page = $this->_get_page();

		//零担id
		$gtid=empty($_GET['gtid'])?0:intval($_GET['gtid']);


        $sql = "select gs.*,op.o_name,ws.ws_new from (zys_goods_normal_sub as gs left join zys_operator as op on gs.g_carrier = op.o_tid) left join zys_waybill_sub_normal as ws on ws.ws_gstid = gs.gs_tid where gs_gtid = ".$gtid ." group by gs.gs_tid";

		$less = $this->_goodsnormalsub_mod->getAll($sql);

		$page['item_count'] = count($less);

		$this->_format_page($page);
		$this->assign('page_info', $page);
		
        $this->assign('gs_gtid', $gtid);

        $this->assign('less', $less);
		
        $this->display('goodsless.chooseless.html');
    }
    //拆箱处理
    function goodslessdone(){
        $db=&db();
        //$arrs = isset($_POST['num']) ? $_POST['num'] : '';
        $checkarrs = isset($_POST['cnum']) ? $_POST['cnum'] : '';
        $gtid =isset($_POST['gs_gtid']) ? intval($_POST['gs_gtid']) : 0;
        $carrier =isset($_POST['g_carrier']) ? intval($_POST['g_carrier']) : 0;
        if(empty($carrier)){
            $this->show_warning('请选择承运商','','index.php?app=goodsless&act=add&id='.$gtid);
            return;
        }
        /*if(empty($checkarrs)){
            $this->show_warning('请选择需要处理的集装箱');
            return;
        }*/
        if($checkarrs!=null&&count($checkarrs)>0){
            foreach ($checkarrs as $k=>$v){
                $sql="select * from zys_goods_normal_sub where gs_tid=".$k;
                $info=$db->getRow($sql);
                if(empty($info)){
                    $this->show_warning('操作错误','','index.php?app=goodsless&act=add&id='.$gtid);
                    return;
                }
				//指派
				$sql="UPDATE zys_goods_normal_sub SET g_carrier=".$carrier." WHERE gs_tid=$k";
				$db->query($sql);

                /*if($arrs[$k] > $info['g_volume']){
                    $this->show_warning('请重新拆分数据');
                    return;
                }elseif($arrs[$k] == $info['g_volume']){
                    //update
                    $sql="UPDATE zys_goods_trunk_sub SET g_carrier=".$carrier." WHERE gs_tid=$k";
                    $db->query($sql);
                }else{
                    //insert
                    $data = array(
                        'gs_gtid'=>$gtid,
                        'g_box' => $info['g_box'],
                        'g_volume' => $arrs[$k],
                        'g_ctn_no'=>$info['g_ctn_no'],
                        'g_eir_code'=>$info['g_eir_code'],
                        'g_carrier'=>$carrier,
                        'g_gstid' => $k
                    );
                    $this->_goodstrunksub_mod->add($data);
                    //update
                    $volume = intval($info['g_volume'] - $arrs[$k]);
                    $sql="UPDATE zys_goods_trunk_sub SET g_volume=".$volume." WHERE gs_tid=$k";
                    $db->query($sql);
                }*/
                unset($info);
            }
        }
        echo("<script>window.parent.location.href='index.php?app=goodsless&act=add&id=".$gtid."';</script>");
    }


    //取消提交货物
	/*
    function remove(){
        try{
            $gtid = isset($_POST['gtid']) ? intval($_POST['gtid']) : 0;
            if(empty($gtid)){
                throw new Exception('操作失败');
            }
            $db=&db();
            $sql = "select *  from zys_goods_trunk_sub where g_gstid !='' and gs_gtid=".$gtid;
            $data = $db->getAll($sql);

           	if(!empty($data)){
				foreach($data as $val){
					$gstid = $val['g_gstid'];
					$num = $val['g_volume'];
					//update
					$sql = "UPDATE zys_goods_trunk_sub SET g_volume = g_volume + $num WHERE gs_tid=$gstid";
					$db->query($sql);
					//删除
					$delsql = "delete from zys_goods_trunk_sub where gs_tid = ".$val['gs_tid'];
					$db->query($delsql);
				}
			}
            $this->json_result(array(),'取消成功');

        }catch (Exception $e){
            $this->json_error($e->getMessage());
        }
    }*/

	//ajax 货物删除
	function delsub(){
		$id = isset($_POST['id']) ? trim($_POST['id']) : '';
		if(empty($id)){
			$this->json_result(array(),'操作错误');
		}
		if (!$this->_goodsnormalsub_mod->drop($id))
		{
			$this->json_error($this->_goodsnormalsub_mod->get_error());
			return;
		}
		$this->json_result(array(),'删除成功');
	}
	//删除
	function drop(){
		$arr = isset($_GET['id']) ? trim($_GET['id']) : '';
		$db=&db();
		$arrs=explode(',', $arr);
		$ids = implode(',',array_filter($arrs));
		if($arrs!=null&&count($arrs)>0){
			try{
				foreach($arrs as $val){
					$sql_goods_normal_sub = "delete from zys_goods_normal_sub where gs_gtid=".$val;
					$db->query($sql_goods_normal_sub);
				}
				$sql_normal = "delete from zys_goods_normal where g_tid in(".$ids.")";
				$db->query($sql_normal);
				$this->show_message('删除成功',	'返回列表', 'index.php?app=goodsless&act=index');
			}catch (Exception $e){
				$this->show_warning($e->getMessage(),	'返回列表', 'index.php?app=goodsless&act=index');
			}
		}else{
			$this->show_message('请选择删除项',	'', 'index.php?app=goodsless&act=index');
		}
	}

	//加入到地址管理系统中

	function addaddr($data){
		$addr = & m('addr');
		$addr->add($data);
	}
	//验证地址是否已经存在
	function checkaddr($addr,$userid,$unit){
		$db = &db();
		$sql="select count(*) as num from zys_addr where address='".$addr."' and user_id=".$userid." and unit=".$unit;
		$num = $db->getone($sql);
		return $num;
	}

}